// Requester.js
const config = require('./config');
const util = require('./util.js');
const user = require('./user.js');

/**
 * 请求网络
 * @param obj
 */
function request(obj) {
    return new Promise((resolve, reject) => {
        let requestParam = {
            ...obj,
            data: {
                ...obj.data,
                cSessionId: util.getSessionId(),
                userSource: config.userSource,
                wxVersion: config.version
            },
            url: obj.host ? obj.host : ''
                + config.domain.requestDomain + obj.url,
            success: (res) => {
                // cSessionId已经过期
                if (res.data.code == 1002) {
                    console.log("cSessionId已经过期", "重新联网登录...");
                    return user.requestLogin()
                        .then(() => {
                            console.log("重新登录成功", "再次请求接口...");
                            requestParam.cSessionId = util.getSessionId();
                            wx.request(requestParam);
                        });
                } else {
                    console.log("请求接口成功!");
                    resolve(res.data);
                }
            },
            fail: (res) => {
                reject(res);
            }
        };
        wx.request(requestParam);
    })
}

/**上传图片 */
function uploadFile(obj) {
    return new Promise((resolve, reject) => {
        let requestParam = {
            ...obj,
            formData: {
                ...obj.formData,
                cSessionId: util.getSessionId(),
                userSource: config.userSource,
                wxVersion: config.version
            },
            url: obj.host ? obj.host : ''
                + config.domain.requestDomain + obj.url,
            success: (res) => {
                if (res.data.code === 1002) {
                    // cSessionId已经过期
                    return user.userLogin().then(() => {
                        console.log("重新登录成功", "再次请求接口...");
                        requestParam.cSessionId = util.getSessionId();
                        wx.request(requestParam);
                    });
                } else {
                    console.log("请求接口成功!");
                    resolve(res.data);
                }
            },
            fail: (res) => {
                console.log("请求接口失败!");
                reject(res);
            }
        };
        wx.uploadFile(requestParam);
    });
}

module.exports = {
    request: request,
    uploadFile: uploadFile,
    domain: config.domain,
    service: config.service
};
